<% layout('/layouts/default.html', {title: '单项指标', libs: ['layout','zTree','dataGrid','inputmask','ueditor','validate','fileupload']}){ %>
<div class="main-content">
    <div class="box box-main">
        <div class="box-header">
            <div class="box-title">
                <i class="fa icon-chart"></i> ${text('指标信息')}
            </div>
            <a style="float: right;display: none" href="#" class="btn btn-default" id="btnExport" onclick="exportExecl()"><i class="glyphicon glyphicon-export"></i> ${text('导出')}</a>
            <#form:form id="searchForm1" model="${dcSupExamSumQuotaInfo}" action="${ctx}/score/dcSupExamDXZBScore/findDXListData" method="post" class="form-inline"
            data-page-no="${parameter.pageNo}" data-page-size="${parameter.pageSize}" data-order-by="${parameter.orderBy}">
            <div style="float: right">
                <#form:hidden path="examId"/>
            </#form:form>
        </div>
    </div>
    <div class="box-body">
        <table id="dataGrid"></table>
        <div id="dataGridPage"></div>
    </div>
</div>
</div>

<div class="ui-layout-center">
    <div class="main-content">
        <form class="form-horizontal" id="inputForm2">
        <div class="box box-main">
            <div class="box-header">
                <div class="box-title">
                    <i class="fa icon-chart"></i> ${text('单位评分信息')}
                </div>
                <div style="float: right" class="form-inline">
                    <div class="form-group" style="margin-right: 20px;">
                        <label class="control-label">${text('排序')}：</label>
                        <div class="control-inline width-140">
                            <% var items = [{label:'默认排名',value:'0'},{label:'百分比排名',value:'1'},{label:'市直排名',value:'2'},{label:'区县排名',value:'3'}]; %>
                            <#form:select path="sortType" items="${items}"  blankOption="true" data-placeholder="请选择" itemLabel="label" itemValue="value" class="form-control width-120" defaultValue="0"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-primary btn-sm" id="search" onclick="scoreSort()">${text('查询')}</button>
                    </div>
                </div>
            </div>
            <div class="ui-layout-content" id="dynamicTable">
            <table id="dataGrid2"></table>
            </div>
            </div>
        </form>
    </div>
</div>

<div class="ui-layout-center">
    <div class="main-content">
        <form class="form-horizontal" id="inputForm3">
            <div class="box box-main">
                <div class="box-body" id="otherView" style="display: none">
                    <div class="row">
                        <div class="form-unit">${text('其他信息')}</div>
                    </div>
                    <div class="row" style="font-size: 14px">
                        <div class="col-xs-6">
                            <div class="form-group">
                                <label class="control-label col-sm-4" title="">
                                    <span class="required">*</span> ${text('联系人')}：<i class="fa icon-question hide"></i></label>
                                <div class="col-sm-8">
                                    <#form:input id="contactName" value="${dcSupExamVo.dcSupExamScore.contactName}" readonly="${dcSupExamVo.dcSupExamScore.scoreStatus=='2'}" maxlength="5"  class="form-control required" placeholder="联系人"/>
                                </div>
                            </div>
                        </div>
                        <div class="col-xs-6">
                            <div class="form-group">
                                <label class="control-label col-sm-4" title="">
                                    <span class="required">*</span> ${text('联系人电话')}：<i class="fa icon-question hide"></i></label>
                                <div class="col-sm-8">
                                    <#form:input id="contactPhone" value="${dcSupExamVo.dcSupExamScore.contactPhone}" readonly="${dcSupExamVo.dcSupExamScore.scoreStatus=='2'}" maxlength="11" class="form-control required" placeholder="联系电话"/>
                                </div>
                            </div>
                        </div>
                        <div class="col-xs-12">
                            <div class="form-group">
                                <label class="control-label col-sm-2" title="">
                                    <span class="required">*</span> ${text('附件')}：<i class="fa icon-question hide"></i></label>
                                <div class="col-sm-10">
                                    <#form:fileupload id="uploadFile" class="required"  maxUploadNum="1" bizKey="${dcSupExamVo.dcSupExamScore.fileId}" readonly="${dcSupExamVo.dcSupExamScore.scoreStatus=='2'}"  bizType="dcSupExamScore_file"
                                    uploadType="all"  cueWords="请将导出后的文件盖章后导入"/>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="box-footer">
                <div class="row">
                    <div class="col-sm-offset-4 col-sm-8">
                        <button id="subDXScore" style="display: none" type="button" class="btn btn-sm btn-primary" onclick="subDxScore()"><i class="fa fa-check"></i> ${text('提交分数')}</button>&nbsp;
                        <button id="saveDXScore" style="display: none" type="button" class="btn btn-sm btn-default" onclick="saveDxScore();"><i class="fa fa-save"></i> ${text('确认分数')}</button>&nbsp;
                        <button type="button" class="btn btn-sm btn-default btnList" id="btnCancel" onclick="js.closeCurrentTabPage()"><i class="fa fa-reply-all"></i> ${text('关 闭')}</button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<% } %>

<script>
    // console.log('${dcSupExamVo.dcSupExamScore.contactName}')
    let baseopt = {
        showRownum: true,
        datatype:"local",
        editGrid:true,
        sortableColumn: false, // 列表不允许排序
        showFooter: false, // 是否显示底部合计行
        editGridInitRowNum:0,
        data:[],
        autoGridHeight: function(){return 'auto'},
        columnModel: [
            {header:'${text("主键")}',hidden: true, name:'id',width:150, align:"left", frozen:true},
            {header:'${text("scoreInfoId")}',hidden: true, name:'scoreInfoId'},
            {header:'${text("指标分类")}',hidden: true, name:'quotaClass',width:150, align:"left", frozen:true},
            {header:'${text("单位类型")}',hidden: true, name:'orgType', width:50, align:"left", frozen:true},
            {header:'${text("序号")}', name:'sortNum', index:'a.login_code', width:200, align:"center",hidden: true},
            {header:'${text("默认排序")}', name:'orgSort', index:'a.login_code', width:200, align:"center",hidden: true},
            {header:'${text("被考核单位名称")}', name:'exameOrgName', index:'a.user_name', width:200, align:"left"},
            {header:'${text("被考核单位code")}', name:'exameOrg', index:'a.user_name', width:200, align:"center",hidden:true},
            {header:'${text("权数")}', name:'quotaWeight', index:'a.ref_name', width:100, align:"center",
                formatter: function(val, obj, row, act){
                    if (val==null||val==''){val=0;}
                    return parseFloat(val).toFixed(2);
                }
            },
            {header:'${text("本年度目标")}', name:'currentYaerGoal', index:'a.ref_name', width:200, align:"center"},
            {header:'${text("考核方式")}', name:'assessMethod', width:150, align:"left", formatter: function(val, obj, row, act){
                    return js.getDictLabel(${@DictUtils.getDictListJson('dc_exam_assessment')}, val, '', true);
             },unformat: function(val, obj, cell){
                    return obj.colModel.data[obj.rowId];}},
            {header:'得分百分比', name:'percentage', width:120,edittype:'text',editable:true, align:"center",editoptions:{'class':'form-control required',
                    dataInit: function(element){
                        let rowid=$(element).attr("rowid")
                        let data=$('#dataGrid2').dataGrid('getRowData', rowid);
                        $(element).attr("inputvalidate","score")
                        $(element).attr("exameOrgName",data.exameOrgName)
                        $(element).addClass('inputmask').attr({'data-inputmask-alias': "money", 'data-inputmask': "'digits':'2'",'range':'[0,100]'}).inputmask()
                        $(element).on("input",function (e){
                            let inputVal= $(element).val();
                            let quotaScore= accMul(accDiv(parseFloat(inputVal),100),data.quotaWeight);
                            console.log(quotaScore)
                            if (data.quotaClass=="3"){
                                $("#dataGrid2").jqGrid("setCell",rowid,"quotaScore",roundHalfUp(accSub(data.quotaWeight,quotaScore),3));
                            }else {
                                $("#dataGrid2").jqGrid("setCell",rowid,"quotaScore",roundHalfUp(quotaScore,3));
                            }

                            if (parseFloat(inputVal)<100){
                                $("#"+rowid+"_scoreReason").addClass("remarkValidator")
                            }else {
                                $("#"+rowid+"_scoreReason").removeClass("remarkValidator")
                            }
                        })

                        $(element).wrapAll("<div class='input-group'></div>")
                        $(element).after('<span class="input-group-addon">%</span>')
                    }
                },unformat: function(val, obj, cell){
                return $('#'+obj.rowId+'_'+obj.colModel.name, cell).val();},
                formatter: function(val, obj, row, act){
                    if (val==''||typeof val=="undefined"){val="0";}
                    if (val.toString().indexOf("%")!=-1){return val;}
                    return parseFloat(val).toFixed(2)+"%";
                }},
            {header:'${text("分数")}', name:'quotaScore', width:100, editable:false,align:"center",editoptions:{'class':'form-control required',
                    dataInit: function(element){
                    }
                },
                formatter: function(val, obj, row, act){
                    if (val==''||typeof val=="undefined"){val=0;}
                    return parseFloat(val).toFixed(3);
                },
                unformat: function(val, obj, cell){return $('#'+obj.rowId+'_'+obj.colModel.name, cell).val();}
            },
            {header:'${text("排名")}', name:'ranking', width:100, align:"center"},
            {header:'备注', name:'scoreReason', width:220, align:"left",classes:'autoHH',
                editable:true, edittype:'text', editoptions:{'maxlength':'200','placeholder':'备注，限制200字以内','autocomplete':'off','class':'form-control remarkValidator',
                    dataInit:function (element){
                    }

                }, unformat: function(val, obj, cell){return $('#'+obj.rowId+'_'+obj.colModel.name, cell).val();}
            }   ,
            {header:'${text("操作")}', name:'actions', width:100, align:"center",formatter: function(val, obj, row, act){
                    var actions = [];
                    if(row.scoreStatus=='1'&&row.quotaScore!=undefined){
                        actions.push('<a href="#" onclick=xiugaiInfo("'+row.id+'")  class="btn btn-primary btn-xs xg" title="${text("修改")}" >修改</a>&nbsp;');
                    }

                    actions.push('<a href="#" onclick=updateInfo("'+row.id+'")  class="btn btn-primary btn-xs bc" style="display: none" title="${text("保存")}" >保存</a>&nbsp;');
                    return actions.join('');
                }},
        ],
        // 加载成功后执行事件
        ajaxSuccess: function(data){


        }
    }

    function xiugaiInfo(id){
        $('#dataGrid2').dataGrid('editRow', id, {keys:true, focusField:false});
        let xg= $("#"+id).find("a")[0];
        $(xg).css("display","none")
        let bc= $("#"+id).find("a")[1];
        $(bc).css("display","inline")
    }
    function updateInfo(id){
        let data=$('#dataGrid2').dataGrid('getRowData',$('#dataGrid2').dataGrid('getSelectRow'));
        let datas=$('#dataGrid').dataGrid('getRowData',$('#dataGrid').dataGrid('getSelectRow'));
        let percentage = data.percentage;
        if(percentage>parseFloat(100)){
            js.showMessage("输入百分比不可大于100");
            return;
        }
        let dcExamScoreInfo ={"id":data.scoreInfoId,"percentage": data.percentage,"quotaScore":data.quotaScore,"scoreOrg":datas.gradeOrg,"scoreReason":data.scoreReason,"examId":datas.examId}
        log(dcExamScoreInfo)
        let xg= $("#"+id).find("a")[0];
        $(xg).css("display","inline")
        let bc= $("#"+id).find("a")[1];
        $(bc).css("display","none")
        $('#dataGrid2').dataGrid('saveRow',id);
        js.ajaxSubmit({url:"${ctx}/score/dcSupExamDXZBScore/updateScoreInfo",data:dcExamScoreInfo,dataType: 'json',callback:function (data){
                if (data.result=="true"){
                    js.showMessage(data.message);
                    $('#dataGrid2').dataGrid('reloadGrid');
                }else {
                    js.showMessage(data.message);
                    $('#dataGrid2').dataGrid('reloadGrid');
                }
            }})
    }
</script>

<script>
    let selectQuotaId;
    let isEdit;

    $('#dataGrid').dataGrid({
        dataGridPage: $('#dataGridPage'),
        searchForm: $("#searchForm1"),
        autoGridHeight:function (){
            return 300;
        },
        showRownum: true,
        sortableColumn: false, // 列表不允许排序
        columnModel: [
            {header:'${text("主键")}',hidden: true, name:'id', index:'a.id', width:50, align:"left", frozen:true},
            {header:'${text("gradeOrg")}',hidden: true, name:'gradeOrg', width:50, align:"left", frozen:true},
            {header:'${text("gradeOrgName")}',hidden: true, name:'gradeOrgName', width:50, align:"left", frozen:true},
            {header:'${text("任务Id")}',hidden: true, name:'examId', index:'a.id', width:50, align:"left", frozen:true},
            {header:'${text("指标Id")}',hidden: true, name:'quotaInfoId', index:'a.id', width:50, align:"left", frozen:true},
            {header:'${text("指标类别")}', name:'quotaType', index:'a.message_number', width:50, align:"left",formatter: function(val, obj, row, act){
                    return js.getDictLabel(${@DictUtils.getDictListJson('dc_quotaType')}, val, '${text("未知")}', true);}},
            {header:'${text("指标分类")}',hidden: true, name:'quotaClass',width:150, align:"left", frozen:true},
            {header:'${text("目标内容")}', name:'quotaContent', index:'a.task_title', width:150, align:"left"}
        ],
        onSelectRow: function(id, isSelect, event){
            changeGrid2Data(id,0)
        },
        ajaxSuccess: function(data){
            if (data.list!=null && data.list.length>0){
                $("#dataGrid").jqGrid('setSelection',data.list[0].id);
                $('#dataGrid tr').eq(1).addClass('SelectBG')
                $('#dataGrid tr').click(function(){
                    $(this).siblings().removeClass('SelectBG');
                    $(this).addClass('SelectBG');
                })
            }
        }
    });





    function reloadGrid(id,data){
        $("#gbox_" + id).remove();
        $("#dynamicTable").html('<table id="'+id+'"></table>');
        baseopt.data=data;
        baseopt.editGrid=isEdit;
        $('#'+id).dataGrid(baseopt);
    }


    function initScoreView(data,sortType){
        if ( typeof data.score == "undefined" ||data.score==null){
            $("#saveDXScore").show();
            isEdit=true;
        }

        if (typeof data.score !="undefined" && data.score!=null){
            if (data.score.scoreStatus==1){
                $("#saveDXScore").hide()
                isEdit=false;
            }
            if (data.score.scoreStatus==2){
                $("#saveDXScore").hide();
                $("#subDXScore").hide();
                isEdit=false;
            }
        }

        if (typeof data.showSubView !="undefined" && data.showSubView=="1"){
            $("#otherView").hide();
        }
        if (typeof data.showSubView !="undefined" && data.showSubView=="2"){
            $("#subDXScore").show();
            $("#otherView").show();
            $("#btnExport").show();
        }
        if (typeof data.showSubView !="undefined" && data.showSubView=="3"){
            $("#otherView").show();
            $("#subDXScore").hide();
            $("#btnExport").show();
        }
        $("#sortType").val("0").trigger("change");
        //评完分 才可以分数排序
        if (data.score==null){
            $("#sortType").find("option[value=1]").attr("disabled","disabled")
            $("#sortType").find("option[value=2]").attr("disabled","disabled")
            $("#sortType").find("option[value=3]").attr("disabled","disabled")
            $("#search").addClass("disabled").attr("onclick",null)
            $("#sortType").select2();
        }else {
            $("#sortType").find("option[value=1]").removeAttr("disabled")
            $("#sortType").find("option[value=2]").removeAttr("disabled")
            $("#sortType").find("option[value=3]").removeAttr("disabled")
            $("#search").removeClass("disabled").attr("onclick","scoreSort()")
            $("#sortType").val(sortType).select2()
            $("#sortType").select2();
        }
    }


    function accAdd(arg1,arg2){
        var r1,r2,m;
        try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
        try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
        m=Math.pow(10,Math.max(r1,r2))
        return (arg1*m+arg2*m)/m
    }

    function accSub(arg1,arg2){
        var r1,r2,m,n;
        try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
        try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
        m=Math.pow(10,Math.max(r1,r2));
        //last modify by deeka
        //动态控制精度长度
        n=(r1>=r2)?r1:r2;
        return ((arg1*m-arg2*m)/m).toFixed(n);
    }


    //乘
    function accMul(arg1, arg2) {
        var m = 0,
            s1 = arg1.toString(),
            s2 = arg2.toString();
        try {
            m += s1.split(".")[1].length;
        } catch (e) {}
        try {
            m += s2.split(".")[1].length;
        } catch (e) {}
        return (
            (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
            Math.pow(10, m)
        );
    }

    //除
    function accDiv(arg1, arg2) {
        var t1 = 0,
            t2 = 0,
            r1,
            r2;
        try {
            t1 = arg1.toString().split(".")[1].length;
        } catch (e) {}
        try {
            t2 = arg2.toString().split(".")[1].length;
        } catch (e) {}
        with (Math) {
            r1 = Number(arg1.toString().replace(".", ""));
            r2 = Number(arg2.toString().replace(".", ""));
            return (r1 / r2) * pow(10, t2 - t1);
        }
    }

    //四舍五入并且保留几位小数
    function roundHalfUp(num, n) {
        n = n ? parseInt(n) : 0;
        if(n <= 0) {
            return Math.round(num);
        }
        num = Math.round(num * Math.pow(10, n)) / Math.pow(10, n); //四舍五入
        num = Number(num).toFixed(n); //补足位数
        return num;}

    function exportExecl(){
        window.open("${ctx}/score/dcSupExamDXZBScore/exportDxScore?noticeId=${dcSupExamVo.dcSupExamNotice.id}&examId="+$("#examId").val())
    }
</script>


<script>
    function saveScore(){
        //评分数据为空禁止提交评分
        let rowData=$('#dataGrid2').dataGrid('getRowData');
        if (rowData==null || rowData.length==0){
            js.alert('当前指标列表为空禁止提交分数！', {icon: 2}, function(){})
            return;
        }

        for(var i=0;i<rowData.length; i++){delete rowData[i]["actions"]}

        let allData =JSON.stringify(rowData);
        let subData = {"dcSupExamSumQuotaDtoListStr":allData,
            "dcSupExamScore.examId":$("#examId").val(),
            "quotaId":selectQuotaId,
            "dcSupExamNotice.id":'${dcSupExamVo.dcSupExamNotice.id}'
        };
        js.ajaxSubmit({url:"${ctx}/score/dcSupExamDXZBScore/saveDXScore",data:subData,dataType: 'json',callback:function (data){
                if (data.result=="true"){
                    js.showMessage(data.message);
                    $("#dataGrid").jqGrid('setSelection',selectQuotaId);
                }else {
                    js.showMessage(data.message);
                }
        }})
    }

    //普通指标校验
    function saveDxScore(){
                let html=$('#dataGrid2').find('input[inputvalidate=score]');
                let remarks=$('#dataGrid2').find('.remarkValidator');
                let remarksLength200=$('#dataGrid2').find('.maxlength200');

        let hasValid=true;
                let difference50=[];
                let differenceMin=100.00;
                let differenceMAx=0.00;
                for (let i = 0; i <html.length; i++) {
                    let element=$(html[i]);
                    let has= $("#inputForm2").validate().element(element);
                    if (has==false){hasValid=false};
                    let val= parseFloat(element.val());
                    //获取最大最小值
                    if (differenceMin>val){
                        differenceMin=val;
                    }
                    if (differenceMAx<val){
                        differenceMAx=val;
                    }

                    if (parseFloat(val)<50.0){
                        difference50.push(element.attr("exameOrgName"))
                    }
                }
                for (let i = 0; i < remarks.length; i++) {
                    let element=$(remarks[i]);
                    let has= $("#inputForm2").validate().element(element);
                    if (has==false){hasValid=false};
                }

                for (let i = 0; i <remarksLength200.length; i++) {
                    let has= $("#inputForm2").validate().element(remarksLength200[i]);
                    if (has==false){hasValid=false}
                }

                if (hasValid){
                    //最高和最低分差值大于10%，评分低于50%给与提示，但是允许继续提交；
                    if ((html.length>=2)&&(differenceMAx-differenceMin>10)){
                        js.confirm("当前指标最高分和最低分差值大于10%", function (data) {
                            if (difference50.length>0){
                                let units=difference50.join(" ");
                                js.confirm(units+"评分低于50%是否继续提交",function (){
                                    saveScore();
                                })
                            }else {
                                saveScore();
                            }
                        });
                    }else {
                        if (difference50.length>0){
                            let units=difference50.join(" ");
                            js.confirm(units+"评分低于50%是否继续提交",function (){
                                saveScore();
                            })
                        }else {
                            saveScore();
                        }
                    }
             }
        }

    //加减分项专用校验
    function saveDxAddRemoveScore(){
        let remarks=$('#dataGrid2').find('input[inputvalidate=remarks]');
        let hasValid=true;
        for (let i = 0; i < remarks.length; i++) {
            let element=$(remarks[i]);
            let has= $("#inputForm2").validate().element(element);
            if (has==false){hasValid=false};
        }
        if (hasValid){
            saveScore();
        }
    }


    function subDxScore(){
       let validate1= $("#inputForm3").validate().element("#contactName");
       let validate2= $("#inputForm3").validate().element("#contactPhone");
       let validate3= $("#inputForm3").validate().element("#uploadFile");
       if (validate1&&validate2&&validate3){
           subScore();
       }
    }


    function subScore(){
        let subData = {
            "dcSupExamNotice.id":'${dcSupExamVo.dcSupExamNotice.id}',
            "dcSupExamNotice.examId":$("#examId").val(),
            "dcSupExamScore.contactName":$("#contactName").val(),
            "dcSupExamScore.contactPhone":$("#contactPhone").val(),
            "fileUploadIds":$("#uploadFile").val()
        };
        js.ajaxSubmit({url:"${ctx}/score/dcSupExamDXZBScore/subDXScore",data:subData,dataType: 'json',callback:function (data){
                if (data.result=="true"){
                    js.showMessage(data.message);
                    location.reload();
                }else {
                    js.showMessage(data.message);
                }
            }})
    }

    function scoreSort(){
        let sortType = $('#sortType').val();
        let selectId = $('#dataGrid').dataGrid('getSelectRow');
        changeGrid2Data(selectId,sortType)
    }

    function changeGrid2Data(id,sortType) {
        let reqData=$('#dataGrid').dataGrid('getRowData', id);
        reqData.noticeId='${dcSupExamSumQuotaInfo.noticeId}'
        selectQuotaId=reqData.id;
        reqData.sortType=sortType;
        js.ajaxSubmit("${ctx}/score/dcSupExamDXZBScore/findUnitScoreListData", reqData, function (data){
            //此处勿轻易动
            initScoreView(data,sortType);
            reloadGrid("dataGrid2",data.data)
        });
        js.closeLoading(500, true);
    }
</script>

<script>
    jQuery.validator.addMethod("remarkValidator", function(v1,v2) {
        if (v1!=null && typeof v1 !="undefined" && v1.trim() !=''){
            return true
        }
        return false;
    },"扣分原因");

    jQuery.validator.addMethod("maxlength200", function(v1,v2) {
        if ($(v2).val().length>200){
            return false;
        }
        return true;
    },"最多可以输入200个字符");

</script>

<style>
    .autoHH{
        white-space: normal !important;
        height:auto;
        /*vertical-align:text-top;*/
        padding-top:2px;
        word-break:break-all;
    }
    .SelectBG td{
        background: #eaeaea !important;
        background-color: #eaeaea !important;
        color:blue;
    }
</style>


